package cn.school.interceptor;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@Service(value = "loginInterceptor")
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //return false:请求终止
        System.out.println("进入了权限拦截器>>>>>>>>>>>>>>>>");
        System.out.println("拦截uri: " + request.getRequestURI());
        String URI=request.getRequestURI();
        long start=System.currentTimeMillis();
        threadLocal.set(start);
        System.out.println("Interceptor拦截器拦截"+URI+"开始时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(start)));

        if(request.getSession().getAttribute("USER_LOGIN")==null){
//            if (URI.contains("login")||URI.contains("Login")||URI.contains("register")||URI.contains("Register")) {
//                return true;
//            }else if (URI.contains("css")||URI.contains("js")||URI.contains("img")||URI.contains("plugins")){
//                return true;
//            }
            request.setAttribute("msg","您尚未登录，还没有权限访问此页面!");
            System.out.println("不允放行...");
            request.getRequestDispatcher("/s_login/toLogin").forward(request,response);
            return false;
        }
        System.out.println("放行...");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //super.postHandle(request, response, handler, modelAndView);
        System.out.println("拦截了:"+handler+",返回值是:"+modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long end=System.currentTimeMillis();
        String URI=request.getRequestURI();
        System.out.println("Interceptor拦截器拦截"+URI+"结束时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(end)));
        System.out.println("Interceptor拦截器拦截"+URI+"共用时："+(end-threadLocal.get())+"毫秒"+"");
//        super.afterCompletion(request, response, handler, ex);
    }
}
